package com.zyx.concurrentdemo.mytest.c04;

import com.zyx.concurrentdemo.c02basic.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/15 17:51
 * desc: 生产消费模型
 */
public class MessageQueueDemo {
    public static void main(String[] args) {
        MessageQueue queue = new MessageQueue(2);
        for (int i = 0; i < 3; i++) {
            int id = i;
            new Thread(() -> {
                queue.put(new Message(id, "msg =====>>>>> " + id));
            }, "producer" + i).start();
        }
        Sleeper.sleep(4);
        new Thread(()->{
            while (true) {
                Message msg = queue.take();
            }
        }, "consumer").start();
    }
}

@Slf4j(topic = "c.MessageQueue")
class MessageQueue {

    private static final LinkedList<Message> LIST = new LinkedList<>();
    private final int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    /**
     * 存消息
     */
    public void put(Message msg) {
        synchronized (LIST) {
            while (LIST.size() >= this.capacity) {
                try {
                    log.debug("队列已满, 生产者无法生产");
                    LIST.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            LIST.addLast(msg);
            LIST.notifyAll();
            log.debug("已生产消息 {}", msg);
        }
    }

    /**
     * 取消息
     */
    public Message take() {
        synchronized (LIST) {
            while (LIST.isEmpty()) {
                try {
                    log.debug("队列为空, 消费者无法消费");
                    LIST.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Message msg = LIST.removeLast();
            LIST.notifyAll();
            log.debug("已消费消息 {}", msg);
            return msg;
        }
    }
}

class Message {
    private int id;
    private String msg;

    public Message(int id, String msg) {
        this.id = id;
        this.msg = msg;
    }

    public int getId() {
        return id;
    }

    public String getMsg() {
        return msg;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", msg='" + msg + '\'' +
                '}';
    }
}